package com.weiaibenpao.demo.chislim.sport.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.district.DistrictItem;
import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lyf on 2017/8/31/031.
 */

public class PolyLines {
    public final static  int POLYLINE_SUCCESS = 100;
    public final static  int POLYLINE_OVER_SUCCESS=1010;
    private int color = Color.parseColor("#189ff6");
    Context context;
    private LatLonPoint centerLatLng;
    private AMap aMap;
    private PolylineOptions options;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == POLYLINE_SUCCESS) {
                PolylineOptions polygonOptions = (PolylineOptions) msg.obj;
                aMap.addPolyline(polygonOptions);
                Log.e("wlx", "handleMessage: " +polygonOptions.getPoints().size());
            }


        }
    };

    public PolyLines(Context context, AMap aMap) {
        this.context = context;
        this.aMap = aMap;

    }

    public void setColor(int color) {
        this.color = color;

    }

    public PolylineOptions getPolylineOoption() {
        Log.e("lyf", "getPolylineOoption: "+options.getPoints().size() );
        return this.options;
    }

    /**
     *
     * @param cityName 城市名字  注意要有市字
     * @param dis 区县名字
     */
    public void getLatlon(final String cityName, final String dis) {
        Log.e("lyf", "onGeocodeSearched:city ");
        GeocodeSearch geocodeSearch = new GeocodeSearch(context);
        GeocodeQuery geocodeQuery = new GeocodeQuery( dis,cityName);
        geocodeSearch.getFromLocationNameAsyn(geocodeQuery);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

            }
            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                if (i == 1000) {
                    if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null &&
                            geocodeResult.getGeocodeAddressList().size() > 0) {
                        List<GeocodeAddress> geocodeAddressList = geocodeResult.getGeocodeAddressList();
                        GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);

                        for (GeocodeAddress address : geocodeAddressList) {
                            Log.d("lyf", "onGeocodeSearched:city "+address.getCity());
                            if (address.getCity().equals(cityName)) {
                                Log.e("lyf", "onGeocodeSearched:getAdcode "+ geocodeAddress.getAdcode());

                            }else {
                                Log.d("lyf", "onGeocodeSearched:出错0 ");
                            }
                        }


                    } else {
                        Log.d("lyf", "onGeocodeSearched:出错 ");
                        Toast.makeText(context, "地址名出错", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });




    }


    /**
     * @param adCode 高德城市地区编码
     * @param dis
     */
    public void drawLIne(final String adCode, String dis, final Handler handler) {
        aMap.clear();
        options=new PolylineOptions();
        DistrictSearch search = new DistrictSearch(context);
        DistrictSearchQuery query = new DistrictSearchQuery();
        query.setKeywords(dis);//传入关键字
        //query.setPageNum();
        query.setShowBoundary(true);//是否返回边界值
        search.setQuery(query);
        search.setOnDistrictSearchListener(new DistrictSearch.OnDistrictSearchListener() {
            @Override
            public void onDistrictSearched(DistrictResult districtResult) {
                //在回调函数中解析districtResult获取行政区划信息
                //在districtResult.getAMapException().getErrorCode()=1000时调用districtResult.getDistrict()方法
                //获取查询行政区的结果，详细信息可以参考DistrictItem类。

                if (districtResult == null || districtResult.getDistrict() == null) {
                    return;
                }
                ArrayList<DistrictItem> district = districtResult.getDistrict();
                DistrictItem item = district.get(0);
                if (!TextUtils.isEmpty(adCode)){
                    for (DistrictItem districtItem : district) {

                        if (districtItem.getAdcode().equals(adCode)) {
                            Log.e("wlx22", "getAdcode: "+districtItem.getAdcode()+"===="+adCode );
                            item = districtItem;
                            break;
                        }

                    }
                }
                if (item == null) {
                    return;
                }
                centerLatLng=item.getCenter();
                if (centerLatLng != null) {  //地图加载时就显示行政区域
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(centerLatLng.getLatitude(), centerLatLng.getLongitude()), 13));//13为缩放级别
//                    aMap.moveCamera(CameraUpdateFactory.zoomTo(12));
                }

                final DistrictItem finalItem = item;
                new Thread() {
                    public void run() {

                        String[] polyStr = finalItem.districtBoundary();
                        if (polyStr == null || polyStr.length == 0) {
                            return;
                        }
                        Log.e("lfy", "polyStr length is " + polyStr.length);//浙江是522,上海11 重庆10,天津和北京都是1,河北是1,河南是7
                        for (String str : polyStr) {//当城市是重庆时,这个循环体第九次执行耗费时间竟然接近10秒!!! 原因很简单,因为第九个字符串长度比其他长好几倍!
                            if (((Activity) context).isFinishing()) {
                                return;
                            }
                            String[] lat = str.split(";");
                            PolylineOptions polygonOptions = new PolylineOptions();
                            boolean isFirst = true;
                            LatLng firstLatLng = null;
                            for (String latstr : lat) {
                                if (((Activity) context).isFinishing()) {
                                    return;
                                }
                                if (polyStr.length>100&&lat.length<70){
                                    continue;
                                }
                                String[] lats = latstr.split(",");
                                polygonOptions.add(new LatLng(Double .parseDouble(lats[1]), Double.parseDouble(lats[0])));
                                if (isFirst) {

                                    isFirst = false;
                                    firstLatLng = new LatLng(Double.parseDouble(lats[1]), Double.parseDouble(lats[0]));
                                    continue;
                                }

                            }
                            if (firstLatLng != null) {
                                polygonOptions.add(firstLatLng);
                            }

                            /**
                             * 把所有的点存起来
                             */
                            options.addAll(polygonOptions.getPoints());

                            /**
                             * 主线程中绘制
                             */
                            polygonOptions.width(12).color(color);
                            Message message = Message.obtain();
                            message.obj=polygonOptions;
                            message.what=POLYLINE_SUCCESS;
                            mHandler.sendMessage(message);
                        }
                            //自适应缩放
                            animate(options);
                        /**
                         * 把所有点集合给调用者
                         */
                        Message message = Message.obtain();
                        message.obj=options;
                        message.what=POLYLINE_OVER_SUCCESS;
                        handler.sendMessage(message);


                    }
                }.start();
            }
        });//绑定监听器

        search.searchDistrictAsyn();
    }

    private void animate(PolylineOptions options) {
        LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();//存放所有点的经纬度
        int num = options.getPoints().size();
        Log.e("lyf", "animate: "+options.getPoints().size() );
        for (int i = 0; i < num; i++) {
            boundsBuilder.include(options.getPoints().get(i));//把所有点都include进去（LatLng类型）
        }
        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), 15));//第二个参数为四周留空宽度

    }
}
